package edu.unika.aifb.graphindex.importer.db.metadata;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Database implements Serializable{
	private static final long serialVersionUID = -5295824197179728544L;
	private Map<String, Table> tables = new HashMap<String, Table>();
	
	public Database(){
	}
	
	public void addTable(Table table){
		this.tables.put(table.getName(), table);
	}
	
	public Table getTable(String tableName){
		return tables.get(tableName);
	}
	
	public List<Table> getTables() {
		return new ArrayList<Table>(tables.values());
	}
	
	public List<String> getTableNames(){
		return new ArrayList<String>(tables.keySet());
	}
	
	public Table getSourceTable(String foreignKey){
		for(Table table : tables.values()){
			if(table.getForeignKeyNames().contains(foreignKey)){
				return table;
			}
		}
		return null;
	}
	
	public Table getTargetTable(String foreignKey){
		for(Table table : tables.values()){
			ForeignKeyConstraint foreignKeyConstraint = table.getForeignKeyConstraint(foreignKey);
			if(foreignKeyConstraint != null)
				return foreignKeyConstraint.getTargetColumns().get(0).getTable();
		}
		return null;
	}
	
	public void print(){
		StringBuffer sb = new StringBuffer();
		for(Table table : this.getTables()){
			if(table.getSchema() != null)
				sb.append(table.getSchema()).append(".");
			sb.append(table.getName()).append("\n");
			for(Column column : table.getColumns()){ 
				sb.append(column.getName()).append("(");
				sb.append(column.getType()).append(") ");
				if(column.isPrimaryKey()){
					sb.append("(PK)");
				}
				if(table.isForeignKey(column)){
					sb.append("(");
					for(String foreignKey : table.getForeignKeyNames()){
						ForeignKeyConstraint foreignKeyConstraint = table.getForeignKeyConstraint(foreignKey);
						if(!foreignKeyConstraint.getSourceColumns().contains(column))
							continue;
						for(int i = 0; i < foreignKeyConstraint.getSourceColumns().size(); i++){
							Column sourceColumn = foreignKeyConstraint.getSourceColumns().get(i);
							if(!sourceColumn.equals(column))
								continue;
							Column targetColumn = foreignKeyConstraint.getTargetColumns().get(i);
							sb.append(foreignKeyConstraint.getName()).append("->").append(targetColumn.getTable().getName()).append(".").append(targetColumn.getName()).append(" "); 
						}
					}
					sb.append(")");
				}
				sb.append("\t");
			}
			sb.append("\n");
			sb.append("\n");
		}
		System.out.println(sb.toString());
	}
	
}
